package item

import (
	"fmt"
	log2 "github.com/name5566/leaf/log"
	"server/db"
)

const (
	TBL_ITEM = "t_items"
)

type ItemDao struct {
	db *db.MongoMiddleware
}

func NewItemDao() *ItemDao {
	return &ItemDao{db: db.Db}
}

// 插入新物品
func (i *ItemDao) InsertItem(playerID string, item Item) error {
	item.PlayerID = playerID
	err := i.db.Insert(TBL_ITEM, item)
	if err != nil {
		return fmt.Errorf("插入物品失败: %v", err)
	}
	return nil
}

// 查询物品
func (i *ItemDao) QueryItems(playerID string, filter map[string]interface{}) ([]Item, error) {
	filter["player_id"] = playerID
	var items []Item
	err := i.db.Find(TBL_ITEM, filter, &items)
	if err != nil {
		return nil, fmt.Errorf("查询物品失败: %v", err)
	}
	return items, nil
}
func (i *ItemDao) QuerySortedItems(playerID string, sortField string, descending bool) ([]Item, error) {
	filter := map[string]interface{}{
		"player_id": playerID,
	}
	sortOrder := 1
	if descending {
		sortOrder = -1
	}
	var items []Item
	err := i.db.FindSort(TBL_ITEM, filter, &items, sortOrder, sortField)
	//err := db.Db.Client.Collection(TBL_ITEM).Find(context.Background(), filter).Sort(fmt.Sprintf("%d%s", sortOrder, sortField)).All(&items)
	if err != nil {
		return nil, fmt.Errorf("排序查询物品失败: %v", err)
	}
	return items, nil
}

// 使用道具
func (i *ItemDao) UseItem(userId string, itemTmpID int, quantity int) error {
	selector := map[string]interface{}{
		"player_id":   userId,
		"item_tmp_id": itemTmpID,
		"usable":      true,
		"quantity":    map[string]interface{}{"$gt": 0},
	}
	update := map[string]interface{}{
		"$inc": map[string]interface{}{"quantity": -quantity},
	}
	err := i.db.Update(TBL_ITEM, selector, update)
	//err := db.Db.Update(ItemTable, selector, update)
	if err != nil {
		log2.Error("使用物品失败: %v", err)
		return fmt.Errorf("使用物品失败")
	}
	log2.Debug("用户id %s 使用了一个道具: %s\n", userId, itemTmpID)
	return nil
}

func (i *ItemDao) AddItem(playerID string, itemTmpID int, quantity int) error {
	selector := map[string]interface{}{
		"player_id":   playerID,
		"item_tmp_id": itemTmpID,
		"usable":      true,
		//"quantity":    map[string]interface{}{"$gt": 0},
	}
	update := map[string]interface{}{
		"$inc": map[string]interface{}{"quantity": quantity},
	}
	err := i.db.Update(TBL_ITEM, selector, update)
	//err := db.Db.Update(ItemTable, selector, update)
	if err != nil {
		log2.Error("添加物品失败: %v select is %v, update is %v", err, selector, update)
		return fmt.Errorf("添加物品失败")
	}
	log2.Debug("用户id %s添加了一个道具: %s\n", playerID, itemTmpID)
	return nil
}
func (i *ItemDao) CraftItem(playerID string, newItemName, newItemCategory string, components []string) error {
	// 检查是否拥有所有组件
	for _, component := range components {
		filter := map[string]interface{}{
			"player_id": playerID,
			"name":      component,
			"quantity":  map[string]interface{}{"$gt": 0},
		}
		var item Item
		err := i.db.Find(TBL_ITEM, filter, &item)
		if err != nil {
			log2.Error("缺少组件: %s", component)
			return fmt.Errorf("缺少组件")
		}
	}

	// 扣除组件
	for _, component := range components {
		selector := map[string]interface{}{
			"player_id": playerID,
			"name":      component,
		}
		update := map[string]interface{}{
			"$inc": map[string]interface{}{"quantity": -1},
		}
		err := i.db.Update(TBL_ITEM, selector, update)
		if err != nil {
			log2.Error("扣除组件失败: %v", err)
			return fmt.Errorf("扣除组件失败")
		}
	}

	// 插入新合成的道具
	newItem := Item{
		Name:        newItemName,
		Category:    newItemCategory,
		Quantity:    1,
		Usable:      true,
		PlayerID:    playerID,
		CraftedFrom: components,
	}
	err := i.db.Insert(playerID, newItem)
	if err != nil {
		log2.Error("扣除组件失败: %v", err)
		return fmt.Errorf("合成新道具失败: %v", err)
	}

	log2.Debug("合成了新道具: %s\n", newItemName)
	return nil
}
